﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace System.Windows.Media.DirectShow
{
    internal class MediaSample : IMediaSample, IUnknown
    {

        private byte[] _data;
        private AMMediaType _mediaType;
        private MemAllocator allocator;

        public MediaSample(MemAllocator allocator)
        {
            this.allocator = allocator;
        }

        //public MediaSample(TimeSpan startMediaTime, TimeSpan endMediaTime)
        //{
        //    _startMediaTime = startMediaTime;
        //    _endMediaTime = endMediaTime;
        //}

        protected internal void InitData()
        {
            _data = new byte[this.Length];
        }

        #region IMediaSample Members

        public byte[] Data
        {
            get { return _data; }
        }

        public long Length
        {
            get;
            set;
        }

        public long StartMediaTime
        {
            get;
            set;
        }

        public long EndMediaTime
        {
            get;
            set;
        }

        public AMMediaType MediaType
        {
            get { return _mediaType; }
            set { _mediaType = value; }
        }

        public TimeSpan StartTime
        {
            get;
            set;
        }

        public TimeSpan EndTime
        {
            get;
            set;
        }

        #endregion

        #region IUnknown Members

        private int counter = 0;

        void IUnknown.AddRef()
        {
            Interlocked.Increment(ref counter);
            //Debug.WriteLine("{0} : {1}", this.GetHashCode(), counter);
        }

        void IUnknown.Release()
        {
            Interlocked.Decrement(ref counter);
            //Debug.WriteLine("{0} : {1}", this.GetHashCode(), counter);

            if (counter == 0)
            {
                allocator.ReleaseBuffer(this);
            }
            else
                if (counter < 0)
                    throw new InvalidOperationException();
        }

        #endregion
    }
}
